import { Injectable, NestMiddleware, Header } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import { PRIVATE_JWT_SECRET_KEY, token_type } from '@/config/jwt'

import { PassportModule } from '@nestjs/passport';
import { JwtService, } from '@nestjs/jwt';

@Injectable()
export class JwtMiddlewares implements NestMiddleware {

  constructor(private jwtService: JwtService) { }
  async use(req: Request, res: Response, next: NextFunction) {
    const token = req.header('Authorization')?.replace(token_type + ' ', '');

    if (!token) {
      return res.status(401).json({ message: 'Access denied. No token provided.' });
    }

    try {
      const payload = await this.jwtService.verifyAsync(
        token,
        {
          secret: PRIVATE_JWT_SECRET_KEY,
        }
      );
      req.headers['state'] = payload
      next();
    } catch (error) {
      res.status(401).json({ message: `Invalid token. #${error}` });
    }
  }
}